
onLoad = function() {
    $('calculateCombatButton').observe('click', submitCombatForm);
    setDefaultData();
};

var BarChart = Class.create({
    initialize: function(element, height, width, distribution) {
        $(element).update('<div style="height=' + height + '; width=' + width + 'px" />');
        var innerDiv = $(element).firstDescendant();
        var divHeight = 15; //height / distribution.length;
        var startZeroRange = null;
        for (var i = distribution.length - 1; i >= 0; i--) {
            var probability = distribution[i].probability;
            if (probability < 0.00001) {
                if (startZeroRange == null) {
                    startZeroRange = distribution[i].value;
                }
                continue;
            }
            var value = distribution[i].value + "";

            var color = this.getColor(distribution[i].value);
            var divWidth = probability * width;   
            divWidth = divWidth < 1 ? 1 : divWidth; // 1px min too avoid css ignore
            var valueSpan = new Element('span').setStyle({height: '100%', width: 20}).update(value);
            var probabilityContainer = new Element('div', {'class': 'probability'}).setStyle({height: '100%', 'width': width - 20}).update(' :' + toPercentageString(probability));
            var bar = new Element('div', {'class': "bar"});
            bar.setAttribute('style', 'height: ' + divHeight + 'px; width: ' + divWidth + 'px; background-color: rgb(' + color.red + ',' + color.green + ',' + color.blue + ')');
            
            bar.insert(valueSpan);
            bar.insert(probabilityContainer);
            innerDiv.insert(bar);
        }
    },
    
    getColor: function(margin) {
        var color = { red: 255, green: 255, blue: 0}; // yellow
        if (margin > 0) {
           color.red -= margin * 50;
        } else {
           color.green += margin * 50;
        }
        return color;
    }
});

submitCombatForm = function() {
    var url = "calculateCombat.wpd?" + $('attackerForm').serialize() + '&' + $('defenderForm').serialize();
    new Ajax.Request(url, {
        method: 'GET',
        onComplete: function(response) {
            var combatResult = response.responseJSON.combatResult;
            $('probabilityGoodGuysBreak').update(toPercentageString(response.responseJSON.probabilityGoodGuysBreak));
            $('probabilityBadGuysBreak').update(toPercentageString(response.responseJSON.probabilityBadGuysBreak));
            new BarChart('combatResultContainer', 200, 500, combatResult);
            new BarChart('goodGuysWoundsCaused', 200, 500, response.responseJSON.goodGuysWoundsCaused);
            new BarChart('badGuysWoundsCaused', 200, 500, response.responseJSON.badGuysWoundsCaused);
            new BarChart('staticCombatResult', 200, 500, response.responseJSON.staticCombatResult);
        }
    });
}

var units = {
    skullcrushers: {
        name: "Skullcrushers",
        modelCount: 4,
        fileSize: 4,
        staticCombatBonus: 0,
        musician: true,
        rerollBreakTest: true,
        coldBlooded: false,
        profile: { ws: 5, st: 5, to: 5, wo: 2, at: 3, ld: 8, us: 1, asv: 1, wsv: 7 },
        mount: { ws: 5, st: 5, in: 2, at: 2 }
    },
    
    mournfang: {
        name: "Mournfang",
        modelCount: 4,
        fileSize: 4,
        staticCombatBonus: 0,
        musician: true,
        rerollBreakTest: true,
        coldBlooded: false,
        profile: { ws: 3, st: 4, to: 4, wo: 3, at: 3, ld: 8, us: 1, asv: 2, wsv: 7 },
        mount: { ws: 3, st: 5, in: 2, at: 4 }
    },

    nightGoblins: {
        name: "Night goblins",
        modelCount: 35,
        fileSize: 5,
        staticCombatBonus: 4,
        musician: true,
        rerollBreakTest: true,
        coldBlooded: false,
        profile: { ws: 2, st: 3, to: 3, wo: 1, at: 1, ld: 9, us: 1, asv: 5, wsv: 7 }
    },

    swordmasters: {
        name: "Swordmasters of Hoeth",
        modelCount: 14,
        fileSize: 7,
        staticCombatBonus: 2,
        musician: true,
        rerollBreakTest: true,
        coldBlooded: false,
        profile: { ws: 6, st: 5, to: 3, wo: 1, at: 2, ld: 2, us: 1, asv: 5, wsv: 7 }
    },
    
    kroxigors: {
        name: "Kroxigors",
        modelCount: 4,
        fileSize: 4,
        staticCombatBonus: 0,
        musician: false,
        rerollBreakTest: false,
        coldBlooded: true,
        profile: { ws: 3, st: 7, to: 4, wo: 3, at: 3, ld: 8, us: 3, asv: 4, wsv: 7 }
    },
    
    knightsErrant: {
        name: "Knights Errant",
        modelCount: 6,
        fileSize: 5,
        staticCombatBonus: 2,
        musician: true,
        rerollBreakTest: true,
        coldBlooded: false,
        profile: { ws: 3, st: 5, to: 3, wo: 1, at: 1, ld: 7, us: 2, asv: 2, wsv: 5 },
        mount: { ws: 3, st: 3, in: 3, at: 1 }
    }
}

var setDefaultData = function() {
    fillForm("goodGuys", units.mournfang);
    fillForm("badGuys", units.skullcrushers);
}

var toPercentageString = function(num) {
    return Math.round(num * 100 * Math.pow(10,5))/Math.pow(10,5) + '%';
}

var fillForm = function(prefix, obj) {
    for (var p in obj) {
        if (typeof obj[p] == 'object') {
            fillForm(prefix + "." + p, obj[p]);
        } else if (typeof obj[p] == 'string' || typeof obj[p] == 'number' || typeof obj[p] == 'boolean') {
	        console.log(prefix + "." + p + ": " + obj[p]);
            $(prefix + "." + p).setValue(obj[p]);	        
        }
    }
}